package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.ProjectGuideInfo;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.StringUtil;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.ElectricGuidePdfAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.util.List;

//  作业指导书 搜索
public class PDF_Search_Activity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "PDF_Search_Activity";
    LinearLayout layout_back;
    EditText et_search;
    Button bt_search;
    ListView lv_guide_book;
    ImageView iv_delectText, iv_img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_search);
        setView();
    }
    public void setView(){
        layout_back = findViewById(R.id.layout_back);
        et_search = findViewById(R.id.et_search);
        bt_search = findViewById(R.id.bt_search);
        iv_delectText = findViewById(R.id.iv_delectText);
        lv_guide_book = findViewById(R.id.lv_guide_book);
        iv_img = findViewById(R.id.iv_img);
        setViewListen();
    }
    public void setViewListen(){   // 设置监听事件
        layout_back.setOnClickListener(this);
        iv_delectText.setOnClickListener(this);
        bt_search.setOnClickListener(this);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                Log.d(TAG, "afterTextChanged: "+s);
                if (s.toString().equals("")){
                    iv_delectText.setVisibility(View.GONE);
                    iv_img.setVisibility(View.VISIBLE);
                    setAdapterByPdf(null);
                }else {
                    iv_delectText.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_delectText:
                et_search.setText("");
                break;
            case R.id.bt_search:
                String str_search = et_search.getText().toString();
                if (StringUtil.isEmptyStr(str_search)){
                    ToastUtils.warnShowLong(getApplicationContext(),"请输入需要查询的文件名！！！");
                    return;
                }
                if (str_search.equals("010203")){   // 直接退出APP
                    finishApp();
                }
                // 查询指导书信息对象
                ProjectGuideInfo projectGuideInfo = new ProjectGuideInfo();
                projectGuideInfo.setFilename(str_search);
                setSelectGuideInfoByEntity(projectGuideInfo);
                break;
            default:
                break;
        }
    }
    //   指导书 信息
    public void setSelectGuideInfoByEntity(ProjectGuideInfo projectGuideInfo){
        API.selectGuideInfoByEntity(projectGuideInfo, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PDF_Search_Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectGuideInfo> projectGuideInfoList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectGuideInfo>>(){}.getType());
                        System.out.println("----指导书信息----"+projectGuideInfoList);
                        if (projectGuideInfoList == null || projectGuideInfoList.size() == 0){
                            setAdapterByPdf(null);
                            iv_img.setVisibility(View.VISIBLE);
                            ToastUtils.warnShowLong(getApplicationContext(),"没有匹配到该文件名的PDF文件！");
                        }else {
                            setAdapterByPdf(projectGuideInfoList);
                            iv_img.setVisibility(View.GONE);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 适配器设置
    ElectricGuidePdfAdapter guidePdfAdapter;
    public void setAdapterByPdf(List<ProjectGuideInfo> guideInfoList){
        String str_search = et_search.getText().toString();
        lv_guide_book.setVisibility(View.VISIBLE);
        guidePdfAdapter = new ElectricGuidePdfAdapter(PDF_Search_Activity.this, guideInfoList, str_search);
        lv_guide_book.setAdapter(guidePdfAdapter);
        lv_guide_book.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectGuideInfo projectGuideInfo = guideInfoList.get(position);
                Log.d(TAG, "listview 点击事件： ----"+projectGuideInfo);
                Intent intent = new Intent(PDF_Search_Activity.this, PdfShowActivity.class);
                intent.putExtra("pdf_path", projectGuideInfo.getFilepath());
                intent.putExtra("pdf_name", projectGuideInfo.getFilename());
                startActivity(intent);
            }
        });
    }

    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }
    // 退出应用
    private void finishApp(){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }
}